﻿using Microsoft.Extensions.Logging;
using JESAI.Application.Abstractions.Sys;
using JESAI.Application.Abstractions.Sys.Dtos;
using JESAI.AutoMapper.ObjectMapping;
using JESAI.Biz.Data.Commons.Consts;
using JESAI.Biz.Data.Enums;
using JESAI.Caching;
using JESAI.Core.Attributes;
using JESAI.DDD.Services;
using JESAI.Platform.Domain.Sys.Repositories;
using JESAI.Schedule.Hangfire.Abstractions;
using JESAI.Schedule.Hangfire.HandleCenter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JESAI.Biz.Data.Enums.Common;

namespace JESAI.Application.Service.Sys
{
    [AppService]
    public class ScheduleService: ApplicationService, IScheduleService
    {
        private readonly IScheduleRepository _scheduleRepository;
        private CacheManager _cacheManager;
        private readonly ILogger<ScheduleService> _logger;

        public ScheduleService(IScheduleRepository scheduleRepository, CacheManager cacheManager,ILogger<ScheduleService> logger) 
        {
            _scheduleRepository = scheduleRepository;
            _cacheManager = cacheManager;
            _logger= logger;
        }



        public List<ScheduleDto> GetAllSchedule()
        {
            return _cacheManager.GetOrAdd<List<ScheduleDto>>(CacheConst.AllScheduleCacheKey,
                (val) =>
                {                   
                    return _scheduleRepository._DbQueryable.Where( p=> p.IsValid == YesOrNo.Yes).ToList().MapTo<List<ScheduleDto>>(); 
                });
        }

        public List<ScheduleDto> GetAllAutoStartSchedule()
        {
            return _cacheManager.GetOrAdd<List<ScheduleDto>>(CacheConst.AllScheduleCacheKey,
                (val) =>
                {
                    return _scheduleRepository._DbQueryable.Where
                    (p=>p.IsAutoStart==YesOrNo.Yes && p.IsValid==YesOrNo.Yes).ToList().MapTo<List<ScheduleDto>>(); 
                });
        }

        public void StartAllAutoStartJob()
        {
            List<ScheduleDto> list = GetAllAutoStartSchedule();
            foreach (ScheduleDto schedule in list)
            {
                _logger.LogInformation($"定时任务【{schedule.Name}】启动!");
                ScheduleHandle scheduleHandle = new ScheduleHandle();
                scheduleHandle.StartJob(schedule.MapTo<ScheduleOprions>());
            }          
        }

        public async void LoadAllScheduleToCacheAsync()
        {
            _cacheManager.Del(CacheConst.AllScheduleCacheKey);
            var allSchedules = await _scheduleRepository.GetListAsync();
            _cacheManager.Set(CacheConst.AllScheduleCacheKey, allSchedules);
        }
    }
}
